import functools
import logging

from google.appengine.api import users


_log = logging.getLogger(__name__)


def require_admin(method):
    """Require that the user be logged in as an administrator.
    
    Google App Engine provides similar functionality:
        from google.appengine.ext.webapp.util import login_required

    But Google's decorator only seems to work for GET request handler methods.
    """
    @functools.wraps(method)
    def wrap(self, *args, **kwds):
        admin = users.is_current_user_admin()
        if not admin:
            # The user isn't logged in as an administrator.
            method_name = method.func_name
            if method_name == 'get':
                # The non-admin user issued a GET request.  Redirect to a login
                # page that redirects back to the current URL (corresponding to
                # the decorated method).
                current_url = self.request.url
                login_url = users.create_login_url(current_url)
                self.redirect(login_url)
            else:
                # The non-admin user issued a POST, PUT, HEAD, OPTIONS, DELETE,
                # or TRACE request.
                pass
        else:
            # The user is logged in as an administrator.  Fall through to the
            # decorated method.
            return method(self, *args, **kwds)
    return wrap
